package com.nike.amoeba.ui.frg

import android.os.Bundle
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.nike.amoeba.MainActivity
import com.nike.amoeba.R
import com.nike.amoeba.base.BaseFragment
import com.nike.amoeba.bean.AppRoomDataBase
import com.nike.amoeba.databinding.FRfidConfigBinding
import com.nike.amoeba.ext.showLoading
import com.nike.amoeba.ext.showMessage
import com.nike.amoeba.viewmodel.SettingModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * User: Nike
 *  2024/3/20 17:08
 */
class RfidConfigFrg: BaseFragment<SettingModel, FRfidConfigBinding>() {

    val configDao = AppRoomDataBase.get().getConfigDao()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.rfid_power.set(getString(R.string.settingAntennaPower_title))
        mViewModel.rfid_power2.set(getString(R.string.other_power))

        mViewModel.viewModelScope.launch(Dispatchers.IO) {
            val configBean = configDao.findFirst()
            withContext(Dispatchers.Main) {
                mDatabind.seekbar.progress = configBean.rfidPower
                mDatabind.seekbar2.progress = configBean.otherPower
            }
        }

        mDatabind.seekbar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener{

            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                mViewModel.rfid_power.set(getString(R.string.settingAntennaPower_title) + "：" + p1)
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }
        })
        mDatabind.seekbar2.setOnSeekBarChangeListener(object : OnSeekBarChangeListener{

            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                mViewModel.rfid_power2.set(getString(R.string.other_power) + "：" + p1)
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }
        })
    }

    inner class ProxyClick(){

        fun omSubmit(){
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val configBean = configDao.findFirst()
                configBean.rfidPower = mDatabind.seekbar.progress
                configBean.otherPower = mDatabind.seekbar2.progress
                configDao.update(configBean)
                withContext(Dispatchers.Main) {
                    showMessage(message = getString(R.string.release_success))
                }
            }
        }

    }

}